#include <sys/time.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include "func_record.h"

#define MAX_FUNC_NUMS 65536

struct tstat {
	unsigned idx;
	int duration;
	int cnt;
};

struct func funcs[MAX_FUNC_NUMS] = {0};
struct tstat time_stat[MAX_FUNC_NUMS] = {0};

void record_func(unsigned id, char *name)
{
	if (funcs[id].valid == 1)
		return;
	funcs[id].name = name;
	funcs[id].valid = 1;
	time_stat[id].idx = id;
}

void record_start(unsigned id)
{
	struct timeval start;
    	gettimeofday(&start, NULL);
	time_stat[id].duration -= 1000 * start.tv_sec + start.tv_usec / 1000;
	time_stat[id].cnt++;
}

void record_end(unsigned id)
{
        struct timeval end;
        gettimeofday(&end, NULL);
        time_stat[id].duration += 1000 * end.tv_sec + end.tv_usec / 1000;
}

int cmp(const void * a, const void * b)
{
	return ( ((struct tstat*)b)->duration - ((struct tstat*)a)->duration );
}

void dump_time_stat()
{
	qsort(time_stat, MAX_FUNC_NUMS, sizeof(struct tstat), cmp);
	printf("Time Stat:\n");
	for (int i=0;i<MAX_FUNC_NUMS;++i) {
		if (time_stat[i].duration == 0) {
			break;
		}
		struct func *f = &funcs[time_stat[i].idx];
		printf("%.128s: %d %d\n", f->name, time_stat[i].duration, time_stat[i].cnt);
	}
}
